using System;
using System.Linq;
using System.Windows.Forms;
using DevComponents.DotNetBar.Metro;
using Platform.Model;
using Platform.Model.Repositories;
using Platform.Utilities;
using PlatformManagement.Properties;

namespace PlatformManagement
{
    public partial class LoginForm : MetroForm
    {
        public bool LoginSuccess = false;

        public LoginForm()
        {
            InitializeComponent();
        }

		protected override void OnShown(EventArgs e)
		{
			base.OnShown(e);
			txtUsername.Focus();
		}

        private void LoginFormLoad(object sender, EventArgs e)
        {
			// Lay danh sach sieu thi va Bind du lieu vao combobox cmdMarket
            cmbMarket.DataSource = Market.Objects.ToList();
            cmbMarket.DisplayMember = "MarketName";
            cmbMarket.ValueMember = "Id";

			// Dat con tro vao o username
            txtUsername.Focus();
        }

        private void BtnLoginClick(object sender, EventArgs e)
        {
			// Hien thi thong bao loi neu nguoi dung khong nhap username hay mat khau
			if (txtUsername.Text.Trim() == "" || txtPassword.Text.Trim() == "")
				lblMessage.Text = Resources.LoginForm_BtnLoginClick_Please_input_Username_or_Password;
			else
			{
				// Goi thu tuc check login
			  
			    //MessageBox.Show(Util.Shared.GetMD5(txtPassword.Text));
				var emp = Employee.Objects.CheckLogin(txtUsername.Text, Util.Shared.GetMD5(txtPassword.Text));
                  string s = Util.Shared.GetMD5(txtPassword.Text);
			    
				if (emp == null)
					// Neu login khong thanh cong => thong bao loi
					lblMessage.Text = Resources.LoginForm_BtnLoginClick_Invalid_username_or_password;
				else
				{
					// Da login thanh cong, luu lai nguoi dung va sieu thi da chon
				    lblMessage.Text = Resources.LoginForm_BtnLoginClick_Login_successful_Loading_data;

					WorkSession.Current.CurrentUser = emp;
					WorkSession.Current.LastRefresh = DateTime.Now;
					WorkSession.Current.Market = cmbMarket.SelectedItem as Market;

                    // Lay danh sach Store, article, supplier theo sieu thi da chon
				    WorkContext.Current.Reload();

				    // An form login
					lblMessage.Text = string.Empty;
					Hide();

					// Hien form lam viec chinh
					var mainForm = new MainForm();
					mainForm.Show();
				}
			}
        }
    }
}